import 'dart:async';

import 'package:flutter/material.dart';

class StreamDemo extends StatelessWidget {
  const StreamDemo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('Stream'),
        ),
        body: StreamHomeDemo(),
      ),
    );
  }
}

class StreamHomeDemo extends StatefulWidget {
  StreamHomeDemo({Key key}) : super(key: key);

  _StreamHomeDemoState createState() => _StreamHomeDemoState();
}

class _StreamHomeDemoState extends State<StreamHomeDemo> {
  StreamSubscription _streamSubscriptionDemo;
  StreamController<String> _streamDemo;
  StreamSink _streamSink;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("create a stream");
    // Stream<String> _streamDemo = Stream.fromFuture(fetchData());
    _streamDemo = new StreamController<String>();
    _streamSink = _streamDemo.sink;
    _streamSink.add('aa');
    print("listen");
    _streamSubscriptionDemo =
        _streamDemo.stream.listen(onData, onError: onError, onDone: onDone);
  }

  void onError(error) {
    print('error $error');
  }

  void onDone() {
    print('Done');
  }

  void onData(String data) {
    print('$data');
  }

  void _addAction() async {
    String value = await fetchData();
    _streamDemo.add(value);
  }

  void _pauseAction() {
    _streamSubscriptionDemo.pause();
  }

  void _cancelAction() {
    _streamSubscriptionDemo.cancel();
  }

  void _resumeAction() {
    _streamSubscriptionDemo.resume();
  }

  Future<String> fetchData() async {
    await Future.delayed(Duration(seconds: 3));
    return 'hello @12121';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
          child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
            RaisedButton(
              child: Text('添加'),
              onPressed: _addAction,
            ),
            RaisedButton(
              child: Text('暂停'),
              onPressed: _pauseAction,
            ),
            RaisedButton(
              child: Text('重新开始'),
              onPressed: _resumeAction,
            ),
            RaisedButton(
              child: Text('取消'),
              onPressed: _cancelAction,
            ),
          ])),
    );
  }
}
